import React, { Component } from 'react'
import { View, Text, Navigator } from '@tarojs/components'
import { AtButton, AtForm, AtInput, AtToast } from 'taro-ui'
import Taro from "@tarojs/taro"
import { register } from "../../api";
import { UserId } from '../../util';

interface UserInformation {
  username: string,
  password: string,
  phone: string
}
interface Toast {
  toastText: string,
  toastIcon: string,
  toastIsOpen: boolean,
  toastState: 'success' | 'error' | 'loading'
}
class index extends Component<null, UserInformation & Toast> {
  constructor(args) {
    super(args);
    this.state = {
      username: '',
      password: '',
      phone: '',
      toastIcon: '',
      toastText: '',
      toastIsOpen: false,
      toastState: 'success'
    }
  }
  handlePhoneChange = (e) => {
    this.setState({
      phone: e
    })
    return e;
  }
  handleUserChange = (e) => {
    this.setState({
      username: e
    })
    return e;
  }

  handlePasswordChange = (e) => {
    this.setState({
      password: e
    })
    return e;
  }
  handleSubmit = (e) => {
    register({
      username: this.state.username,
      password: this.state.password,
      phone: this.state.phone
    }).then((res: any) => {
      this.setState({
        toastState: 'success',
        toastIsOpen: true,
        toastText: '注册成功'
      })
      setTimeout(() => {
        this.setState({
          toastIsOpen: false
        })
      }, 1500)
      Taro.redirectTo({
        url: '/pages/login/index'
      })
    }, rej => {
      this.setState({
        toastState: 'error',
        toastIsOpen: true,
        toastText: '注册失败' + rej.msg
      })
      setTimeout(() => {
        this.setState({
          toastIsOpen: false
        })
      }, 1500)
    })
  }


  render() {
    return (
      <View className='wrapper'>
        <Text className='title'>羊羊快递·注册</Text>
        <AtToast isOpened={this.state.toastIsOpen} text={this.state.toastText} icon={this.state.toastIcon} status={this.state.toastState}></AtToast>
        <AtForm>
          <AtInput title="用户名" name="user" type='text' onChange={this.handleUserChange} value={this.state.username} placeholder='请输入您的用户名'></AtInput>
          <AtInput title="密码" name="password" type='password' onChange={this.handlePasswordChange} value={this.state.password} placeholder='请输入密码'></AtInput>
          <AtInput title="手机号" name="phone" type='phone' onChange={this.handlePhoneChange} value={this.state.phone} placeholder='请输入您的手机号'></AtInput>
          <AtButton onClick={this.handleSubmit}>注册</AtButton>
        </AtForm>
      </View>
    );
  }
}

export default index;